package cn.icyzx.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;
import cn.icyzx.service.FindPswService;
import cn.icyzx.util.StaticConstUtil;

/**
 * Created by 郑凯 on 2016/8/27.
 */
@Controller
public class FindPswProcess {

    @Autowired
    FindPswService findPswService;

    @RequestMapping(value = "/find-psw", method = RequestMethod.GET)
    public String forgetWords(ModelMap modelMap) {
        modelMap.put("server", StaticConstUtil.SERVER_NAME);
        modelMap.put("sendEmailTitle", "发送邮件找回密码");
        modelMap.put("sendEmailAction", "find-psw");
        return "sendEmail";
    }

    @RequestMapping(value = "/find-psw", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    @ResponseBody
    String findPassword(@RequestParam("email") String email) {
        if (findPswService.sendFindPsw(email)) return "我们已经向你的邮箱中发送了一一封邮件，请注意查收";
        else return "系统繁忙，请稍后重试";
    }


    @RequestMapping(value = "resetPassword")
    String resetPassword(@RequestParam(value = "resetTip", defaultValue = "") String resetTip, @RequestParam(value = "uid", defaultValue = "") String uid, ModelMap modelMap) {
        modelMap.put("resetTip", resetTip);
        modelMap.put("uid", uid);
        modelMap.put("server", StaticConstUtil.SERVER_NAME);
        return "reSetPassword";
    }

    @RequestMapping(value = "/reset-psw", method = RequestMethod.GET)
    String resetPasswordPage(@RequestParam("findPsw") String findPsw, @RequestParam("uid") String uid, ModelMap modelMap) {

        if (findPswService.checkfindPsw(uid, findPsw)) {
            modelMap.put("uid", uid);
            modelMap.put("server", StaticConstUtil.SERVER_NAME);
            return "reSetPassword";
        } else {
            modelMap.put("loginTip", "此邮件已过期，请重新操作吧o(^▽^)o");
            return "index";
        }
    }

    @RequestMapping(value = "/reset-psw", method = RequestMethod.POST)
    String resetPasswordPageOp(@RequestParam("uid") String uid, @RequestParam("password") String password, ModelMap modelMap) {
        if (password.equals("")) {
            modelMap.put("resetTip", "密码不能为空");
            modelMap.put("uid", uid);
            return "redirect:resetPassword";
        }

        if (findPswService.modifyPsw(password, uid)) {
            modelMap.put("loginTip", "您已修改密码，请重新登陆");
            return "redirect:index";
        } else {
            modelMap.put("resetTip", "发生了错误！");
            modelMap.put("uid", uid);
            return "redirect:resetPassword";
        }
    }

}
